<template>
    <div v-wechat-title="VueTitle">
        <nav class="box clearfix">
			<div class="w-1200 clearfix">
				<div class="left-cont clearfix fl">
					<router-link to="/home" class="logo-box"><img v-if="platformConfig && platformConfig.pc_logo" :src="imgRequest + platformConfig.pc_logo" alt=""></router-link>
				</div>
			</div>   
        </nav>     
        <!-- nav -->
        <div class="main-content-wrap reg-main-bg clearfix">
            <div class="w-1200 reg-wrap clearfix">
                <div class="reg-title">
                    <h2>会员注册</h2>
                </div>
                <div class="reg-content">
                    <Spin fix size="large" v-if="loading"></Spin>
					<Form ref="registerInfo" :model="registerInfo" :rules="registerrule" :label-width="80" label-position="right">
						<FormItem label="账号" prop="userName">
							<Input :maxlength="15" placeholder="请输入6-15位且必须包含英文和数字的账号" v-model="registerInfo.userName" ref="username"></Input>
						</FormItem>
						<FormItem label="密码" prop="psd">
							<Input :maxlength="15" type="password" placeholder="请输入6-15位且必须包含英文和数字的密码" v-model="registerInfo.psd"></Input>
						</FormItem>
						<FormItem label="确认密码" prop="confirmPsd">
							<Input :maxlength="15" type="password" placeholder="请输入确认密码" v-model="registerInfo.confirmPsd" @keyup.enter.native="registerNow('registerInfo')"></Input>
						</FormItem>
						<FormItem label="QQ号码" prop="qq" v-if="OptionalItems.qq">
							<Input placeholder="请输入您的QQ" v-model="registerInfo.qq" ref="qq" @keyup.enter.native="registerNow('registerInfo')"></Input>
						</FormItem>
						<FormItem label="微信" prop="weixin" v-if="OptionalItems.weixin">
							<Input placeholder="请输入您的微信" v-model="registerInfo.weixin" ref="weixin" @keyup.enter.native="registerNow('registerInfo')"></Input>
						</FormItem>
						<FormItem label="手机号码" prop="mobile" v-if=" OptionalItems.mobile">
							<Input :maxlength="11" placeholder="请输入您的手机号码" v-model="registerInfo.mobile" ref="mobile" @keyup.enter.native="registerNow('registerInfo')"></Input>
						</FormItem>
						<FormItem label="邮箱" prop="email" v-if="OptionalItems.email">
							<Input placeholder="请输入您的邮箱" v-model="registerInfo.email" ref="email" @keyup.enter.native="registerNow('registerInfo')"></Input>
						</FormItem>
						<FormItem label="真实姓名" prop="realname" v-if="OptionalItems.realname">
							<Input type="text" v-model="registerInfo.realname" placeholder="请输入您的真实姓名"></Input>
						</FormItem>
						<FormItem label="验证码" prop="register" v-if="OptionalItems.register" class="registerInfo-code">
							<Input placeholder="请输入您的验证码" v-model="registerInfo.register" ref="register" @keyup.enter.native="registerNow('registerInfo')"></Input>
							<img :src="codeUrl" class="verificationCode" @click="verificationCode" ref="codeUrl">
						</FormItem>
						<FormItem label="推荐人" prop="referrercode">
							<Input v-model="registerInfo.referrercode" :disabled="pid?true:false" placeholder="请输入介绍人(可不填)" ref="referrerCode" @keyup.enter.native="registerNow('registerInfo')"></Input>
						</FormItem>
					</Form>
					<div class="log-btn">
						<Button type="error" size="large" :loading="btnLoading" long @click="registerNow('registerInfo')">
							<span v-if="!btnLoading">立即注册</span>
							<span v-else>注册中...</span>
						</Button>
						<div class="autolog-box clearfix">
							<p class="text-center"><router-link to="/login">已有账号？去登录</router-link></p>
						</div>
					</div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import { jsonToString } from "@/common/js/jsonToString";
import { mapGetters, mapActions } from "vuex";
import loginStore from "@/store/loginStore";
//QQ验证
const validateQQ = (rule, value, callback) => {
	if (rule.required && !value) {
		callback(new Error("QQ不能为空"));
	// } else if (!/^[1-9]{1}[0-9]{4,}$/.test(value)) {
	// 	callback(new Error("输入的QQ号码格式错误！"));
	} else {
		callback();
	}
};
//微信验证
const validateWeixin = (rule, value, callback) => {
	if (rule.required && !value) {
		callback(new Error("微信不能为空"));
	// } else if (!/^[a-zA-Z0-9_-]{3,30}$/.test(value)) {
	// 	callback(new Error("输入的微信格式错误！"));
	} else {
		callback();
	}
};
//手机验证
const validateMobile = (rule, value, callback) => {
	if (rule.required && !value) {
		callback(new Error("手机号码不能为空"));
	} else if (!/^[0-9]{11}$/.test(value)) {
		callback(new Error("输入的手机号码格式错误！"));
	} else {
		callback();
	}
};
//邮箱验证
const validateEmail = (rule, value, callback) => {
	if (rule.required && !value) {
		callback(new Error("邮箱不能为空"));
	} else if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
		callback(new Error("输入的邮箱格式错误！"));
	} else {
		callback();
	}
};
//真实姓名验证
const validateRealname = (rule, value, callback) => {
	if (rule.required && !value) {
		callback(new Error("真实姓名不能为空"));
	} else {
		callback();
	}
};
//验证码验证
const validateRegister = (rule, value, callback) => {
	if (rule.required && !value) {
		callback(new Error("验证码不能为空"));
	} else {
		callback();
	}
};
export default {
	data() {
		//账号验证
		const validateUserName = (rule, value, callback) => {
			if (!value) {
				callback(new Error("账号不能为空"));
			} else if (!/^[0-9a-z]{6,15}$/i.test(value)) {
				callback(new Error("请输入6-15位且必须包含英文和数字的账号"));
			} else if (value == this.userName) {
				callback(new Error("账号已存在"));
			} else {
				callback();
			}
		};
		//密码验证
		const validatePsd = (rule, value, callback) => {
			if (value === "") {
				callback(new Error("密码不能为空"));
			} else if (!/^(?![^a-zA-Z]+$)(?!\D+$).{6,15}$/.test(value)) {
				callback(new Error("请输入6-15位且必须包含英文和数字的密码"));
			} else {
				if (this.registerInfo.confirmPsd !== "") {
					this.$refs.registerInfo.validateField("confirmPsd");
				}
				callback();
			}
		};
		//确认密码验证
		const validateConfirmPsd = (rule, value, callback) => {
			if (value === "") {
				callback(new Error("请输入确认密码"));
			} else if (value !== this.registerInfo.psd) {
				callback(new Error("两次密码输入不一致"));
			} else {
				callback();
			}
		};
		//推荐人验证
		const validateReferrercode = (rule, value, callback) => {
			if (value == this.referrer && value !== "") {
				callback(new Error("推荐人不存在"));
			} else {
				callback();
			}
		};
		//登录验证
		const validateLoginUserName = (rule, value, callback) => {
			if (!value) {
				callback(new Error("账号不能为空"));
			} else {
				//  else if (!/^[0-9a-z]{6,15}$/i.test(value)) {
				//   callback(new Error("账号为6-15位字符，必须是字或字母"));
				// }
				callback();
			}
		};
		const validateLoginPsd = (rule, value, callback) => {
			if (value === "") {
				callback(new Error("密码不能为空"));
			} else {
				// else if (!/^(?![^a-zA-Z]+$)(?!\D+$).{6,15}$/.test(value)) {
				//   callback(new Error("请输入6-15位且必须包含英文和数字的密码"));
				// }
				callback();
			}
		};
		return {
			VueTitle: "会员注册",
			loading: true, //注册选项加载
			OptionalItems: {}, //注册选项是否显示
			Optstate: null, //1表示必填 0表示选填
			//注册信息
			registerInfo: {
				userName: "",
				psd: "",
				confirmPsd: "",
				qq: "",
				weixin: "",
				mobile: "",
				email: "",
				realname: "",
				register: "",
				referrercode: ""
			},
			referrer: "",
			registerrule: {
				psd: [{ validator: validatePsd, trigger: "blur", required: true }],
				confirmPsd: [{ validator: validateConfirmPsd, trigger: "blur", required: true }],
				userName: [{ validator: validateUserName, trigger: "blur", required: true }],
				referrercode: [{ validator: validateReferrercode, trigger: "blur" }]
			},
			pid:null,
			type:null,
			codeUrl: '',
			btnLoading: false,
		};
	},
	created() {
		this.browserRedirect();

		this.verificationCode();
		// 注册QQ 微信 手机 邮箱 是否显示必填
		this.pid = this.$route.query.pid;
		var params = {
			id : this.pid ? this.pid : ""
		};
		this.loading = true;
		this.$http.post(this.urlRequest + "?m=api&c=trend&a=getRegInfo", params).then(res => {
			this.loading = false;
			if (res.data.status == 0) {
				this.OptionalItems = res.data.register;
				this.registerInfo.referrercode= res.data.username;
				if (res.data.state == 0) {
					this.Optstate = false;
				} else {
					this.Optstate = true;
				}
			}
		});
	},
	mounted() {
		this.type = this.$route.query.type;
	},
	computed: {
		...mapGetters(['isLogin', 'platformConfig'])
	},
	methods: {
		...mapActions(["SET_ISLOGIN", "SET_USER_INFO_DATA", "SET_ACCOUNT_DATA"]),
		browserRedirect() { //区分PC、H5
            let sUserAgent = navigator.userAgent.toLowerCase();
            let bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
            let bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
            let bIsMidp = sUserAgent.match(/midp/i) == "midp";
            let bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
            let bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
            let bIsAndroid = sUserAgent.match(/android/i) == "android";
            let bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
            let bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
            if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
				this._getLinkUrl();
				console.log('pcmobile')
            } else {
				console.log('pcweb')
            }
        },
		_getLinkUrl() {
			if (this.$route.query.pid && this.$route.query.type) {
				this.linkUrl = this.imgRequest + '/pcmobile/index.html#/reg?pid='+ this.$route.query.pid + '&type=' + this.$route.query.type;
			} else {
				this.linkUrl = this.imgRequest + '/pcmobile/index.html#/reg'
			}
			console.log('链接地址：', this.linkUrl)
			window.open(this.linkUrl, '_self')
		},
		verificationCode() { //点击刷新验证码
			var timestamp = new Date().getTime();
			this.codeUrl = this.imgRequest + '?m=web&c=user&a=validatecode&time=' + timestamp;
		},
		registerNow(registerInfo) { // 立即注册
			this.$refs[registerInfo].validate(valid => {
				if (valid) {
					var params = {
						username: this.registerInfo.userName,
						password: this.registerInfo.psd,
						password2: this.registerInfo.confirmPsd,
						qq: this.registerInfo.qq,
						weixin: this.registerInfo.weixin,
						mobile: this.registerInfo.mobile,
						email: this.registerInfo.email,
						realname: this.registerInfo.realname,
						register: this.registerInfo.register,
						flag: "4",
						code: "123",
						type: this.type ? this.type : "1",
						referrer: this.registerInfo.referrercode
					};
					this.btnLoading = true;
					this.$http.post(this.urlRequest + "?m=api&c=user&a=reg", params).then(res => {
						this.btnLoading = false;
						if (res.data.status == 0) {
							localStorage.setItem("token", res.data.token);
							localStorage.setItem("isLogin", true);
              				localStorage.setItem("isUser", true);
							//注册成功就登录
							this.$http.post(this.urlRequest + "?m=api&c=user&a=userInfo", {token: res.data.token}).then(res => {
								this.SET_USER_INFO_DATA({
								Obj : res.data.data
								})
							})
							localStorage.setItem("userData", JSON.stringify(res.data));
							this.SET_ACCOUNT_DATA({
								Obj: {}
							});
							this.$Message.success("注册成功!");
							this.$router.push({
								path: "/home",
								name: "Home"
							});
						} else if (res.data.status == 1713) { //校验账号是否存在
							this.$refs.username.focus();
							this.userName = this.registerInfo.userName;
							this.$Message.error(res.data.ret_msg);
							var vm = this;
							setTimeout(() => {
								vm.$refs.username.blur();
							}, 20);
						} else if (res.data.status == 100022) { //校验推荐人
							this.$refs.referrerCode.focus();
							this.referrer = this.registerInfo.referrercode;
							this.$Message.error(res.data.ret_msg);
							var vm = this;
							setTimeout(() => {
								vm.$refs.referrerCode.blur();
							}, 20);
						} else {
							this.$Message.error(res.data.ret_msg);
						}
					}).catch(error => {
						this.btnLoading = false;
						this.$Message.error("数据请求超时");
					});
				}
			});
		}
	},
	watch: {
		Optstate(val) { //注册QQ 微信 手机 邮箱 是否显示必填
			if (val) {
				this.registerrule.qq = [{validator: validateQQ, trigger: "blur", required: this.Optstate}],
				this.registerrule.weixin = [{validator: validateWeixin, trigger: "blur", required: this.Optstate}],
				this.registerrule.mobile = [{validator: validateMobile, trigger: "blur", required: this.Optstate}],
				this.registerrule.email = [{validator: validateEmail, trigger: "blur", required: this.Optstate}],
				this.registerrule.realname = [{validator: validateRealname, trigger: "blur", required: this.Optstate}],
				this.registerrule.register = [{validator: validateRegister, trigger: "blur", required: this.Optstate}];
			}
		}
	},
};
</script>
<style scoped>
.registerInfo-code >>> .ivu-form-item-content {
  	padding-right: 115px;
}
.verificationCode {
	position: absolute;
	right: 0;
	top: 1px;
	height: 32px;
}
.right-cont {
    font-size: 28px;
    color: #fff;
}
.reg-main-bg {
	padding: 30px 0;
	/* background: url("../../assets/images/about-content-bg.jpg"); */
	overflow: auto;
	background-size: cover;
}
.reg-wrap {
	padding: 0 3px;
}
.reg-title {
	padding: 0 30px;
	/* background: url("../../assets/images/reg-top.png") no-repeat center top; */
}
.reg-title h2 {
	padding: 30px 0;
	text-align: center;
	color: #424242;
	font-size: 28px;
	line-height: 36px;
	font-weight: 400;
	border-bottom: 1px dotted #ccc;
}
.reg-content {
	position: relative;
	min-height: 600px;
	padding: 30px 350px;
	background: #fff;
	box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.5);
	border-radius: 0 0 8px 8px;
}
.reg-content h3 {
	text-align: center;
	color: #222;
	font-size: 30px;
	line-height: 1.5;
	font-weight: 400;
}
.log-btn p a {
    color: #C82834;
}
.log-btn p a:hover {
    color: #E64254;
}
</style>


// WEBPACK FOOTER //
// src/components/reg/reg.vue